package util;

import com.drew.imaging.tiff.TiffMetadataReader;
import com.drew.metadata.Directory;
import com.drew.metadata.Metadata;
import com.drew.metadata.Tag;
import com.sun.media.jai.codec.*;
import pojo.Tif;

import java.io.File;
import java.io.IOException;
import java.util.Iterator;

/**
 * Created by Administrator on 2016/10/5.
 */
public class TifUtil {

    public static Tif getTifIno(String fileName){
        int page = 0;
        String x = "";
        String y = "";
        String display = "";
        File file = new File(fileName);
        SeekableStream s = null;
        TIFFDecodeParam param = null;
        try {
            s = new FileSeekableStream(file);
            ImageDecoder dec = ImageCodec.createImageDecoder("tiff", s, param);
            page = dec.getNumPages();
        } catch (IOException e1) {
            e1.printStackTrace();
        }finally {
            if(s!=null){
                try {
                    s.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        File jpegFile = new File(fileName);
        try {
            Metadata metadata = TiffMetadataReader.readMetadata(jpegFile);
            Iterable<Directory> a = metadata.getDirectories();
            Iterator<Tag> tag;
            String tagName;
            Tag temp;
            int flag = 0;
            for (Directory directory : a) {
                tag = directory.getTags().iterator();
                while (tag.hasNext()) {
                    if(flag == 3) break;
                    temp = tag.next();
                    tagName = temp.getTagName();
                    if ("X Resolution".equals(tagName)){
                        x = temp.getDescription();
                        flag ++ ;
                    }else if ("Y Resolution".equals(tagName)){
                        y = temp.getDescription();
                        flag ++ ;
                    }else if ("Thumbnail Compression".equals(tagName)){
                        display = temp.getDescription();
                        flag ++ ;
                    }
                }
            }
        }catch (Exception e){

        }finally {

        }

        if(page > 0 && x.length() > 0 && y.length() > 0){
            Tif tif = new Tif();
            tif.setPage(page);tif.setX(x);tif.setY(y);tif.setCompress(display);
            return tif;
        }
        return null;
    }
}
